//
//  HtmlHelper.m
//  iCarStyle
//
//  Created by liu nian on 13-9-11.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "HtmlHelper.h"
#import "TFHpple.h"
#import "Article.h"
#import "ArticleManager.h"
#import "CoreDataManager.h"
#import "PicModel.h"

@implementation HtmlHelper


#pragma mark =====================================================================================
#pragma mark handle data
#pragma mark =====================================================================================
//文章标题
- (NSString *)getTitleWithTitles:(NSArray *)titles atIndex:(NSInteger)index{
    if (index < [titles count]) {
        TFHppleElement *element = [titles objectAtIndex:index];
        NSString *text = [element text];
        return text;
    }
    return nil;
}
//发布时间
- (NSString *)getPublishTimeWithItems:(NSArray *)items atIndex:(NSInteger)index{
    if (index < [items count]) {
        TFHppleElement *element = [items objectAtIndex:index];
        NSString *text = [element text];
        return text;
    }
    return nil;
}

//文章链接
- (NSString *)getLinkWithTitles:(NSArray *)titles atIndex:(NSInteger)index{
    if (index < [titles count]) {
        TFHppleElement *element = [titles objectAtIndex:index];
        NSString *href = [element objectForKey:@"href"];
        return href;
    }
    return nil;
}
//图片
- (NSString *)getImgWithItems:(NSArray *)items atIndex:(NSInteger)index{
    if (index < [items count]) {
        TFHppleElement *element = [items objectAtIndex:index];
        NSString *src = [element objectForKey:@"src"];
        if ([src rangeOfString:@"default120.jpg"].length > 0) {
            return nil;
        }
        
        if ([src rangeOfString:@"upload/Images"].length > 0) {
            src = [src stringByReplacingOccurrencesOfString:@"_120.jpg" withString:@""];
            return src;
        }
        return src;
    }
    return nil;
}
//摘要
- (NSString *)getDescWithItems:(NSArray *)items atIndex:(NSInteger)index{
    if (index < [items count]) {
        TFHppleElement *element = [items objectAtIndex:index];
        NSString *text = [element text];
        text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        text = [text stringByReplacingOccurrencesOfString:@"【车主之家用车知识】" withString:@""];
        return text;
    }
    return nil;
}

//栏目
- (NSString *)getCatalogWithItems:(NSArray *)items atIndex:(NSInteger)index{
    if (index < [items count]) {
        TFHppleElement *element = [items objectAtIndex:index];
        NSString *text = [element text];
        return text;
    }
    return nil;
}
//文章ID
- (NSInteger)getnewNidWithLink:(NSString *)link{
    NSString *fileName = [link lastPathComponent];
    if ([[fileName pathExtension] isEqualToString:@"html"]) {
        return [[fileName stringByDeletingPathExtension] integerValue];
    }
    return 0;
}
//栏目ID
- (NSInteger)getCidWithCatalog:(NSString *)catalog{
    
    if (catalog) {
        __block NSRange range;
        __block NSInteger index = 0;
        NSArray *cNames = [NSArray arrayWithObjects:@"全部",@"美容知识",@"养护知识",@"维修知识",@"改装知识",@"车居知识",@"汽车用品",@"保险知识", nil];
        [cNames enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            range = [catalog rangeOfString:(NSString *)obj];
            if (range.length > 0) {
                index = idx;
            }
        }];
        return index;
    }
    return 0;
}
/*
 
 <dl>
 <dt>
 
 <span class="f_r">2014-04-11</span><a class="f_gray" href="/cjzs/index.html">【车居知识】</a><a href="http://news.16888.com/a/2014/0411/359953.html" target="_blank">汽车车灯图解大全(5)日间行车灯的使用及操作</a><span class="ico_j"><!-- 推荐图标 --></span>
 
 </dt>
 
 <dd>
 <img src="http://image.16888.com/upload/Images/2014/04/2014040910093391374_600.jpg_120.jpg" onerror="this.src='http://image.16888.com/default120.jpg_120.jpg'">
 <span><a href="http://news.16888.com/a/2014/0411/359953.html" target="_blank">阅读全文&gt;&gt;</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;      【车主之家用车知识】汽车灯光的使用与行车安全有着直接的关系，正确使用汽车灯光不仅可以保护自身的安全，同时可以营造出一个井然有序的交通环境。继前几期灯光讲解之后，本期菜鸟进阶课堂我们一起聊聊汽车日间行车灯以及其使用方法。-------------------...</span>
 </dd>
 </dl>
 */
- (void)paserNewsListHtml:(NSURL *)URL itemsBlock:(ItemsBlock)block{
    BMLog(@"url:%@",URL);
    NSData *htmlData;
    NSString *htmlStr = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error:nil];
    htmlData = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];


    OGDocument *document = [ObjectiveGumbo parseDocumentWithData:htmlData];

    NSArray *dls = [document select:@"dl"];
    NSMutableArray *resultArray = [NSMutableArray arrayWithCapacity:dls.count];

    dispatch_queue_t queue = dispatch_queue_create("com.iliunian.icar.data", NULL);
    dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_event_handler(source, ^{
        BMLog(@"%lu",dispatch_source_get_data(source));
    });
    dispatch_resume(source);

    dispatch_apply([dls count], queue, ^(size_t index) {
        // do some work on data at index

        Article *article = [[Article alloc] init];

        NSString *title = nil;
        NSString *catalog = nil;
        NSString *link = nil;
        NSString *img = nil;
        NSString *desc = nil;
        NSInteger nid = 0;
        NSString *date = nil;

        OGElement *rootElement = [dls objectAtIndex:index];

        OGElement *dtElement = [[rootElement select:@"dt"] firstObject];
        OGElement *spanDtElement = (OGElement*)[dtElement first:@"span"];
        date    = [spanDtElement text];

        OGElement *a1DtElement = (OGElement *)[[dtElement select:@"a"] firstObject];
        catalog   = [a1DtElement text];

        OGElement *a2DtElement = (OGElement *)[[dtElement select:@"a"] lastObject];
        title   = [a2DtElement text];


        OGElement *ddElement = [[rootElement select:@"dd"] firstObject];

        OGElement *imgElement = (OGElement*)[ddElement first:@"img"];
        img = imgElement.attributes[@"src"];

        if ([img rangeOfString:@"default120.jpg"].length > 0) {
            img = nil;
        }else if ([img rangeOfString:@"upload/Images"].length > 0) {
            img = [img stringByReplacingOccurrencesOfString:@"_120.jpg" withString:@""];
        }

        OGElement *spanElement = (OGElement*)[ddElement first:@"span"];

        OGElement *aElement = (OGElement*)[spanElement first:@"a"];
        link = aElement.attributes[@"href"];

        nid = [self getnewNidWithLink:link];

        OGText *infoText = (OGText *)spanElement.children[1];
        desc = [infoText text];

        desc = [desc stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        desc = [desc stringByReplacingOccurrencesOfString:@"【车主之家用车知识】" withString:@""];

        article.nid = nid;
        article.title = title;
        article.link = link;
        article.icon = img;
        article.date = date;
        article.desc = desc;
        article.cid = [self getCidWithCatalog:catalog];
        [resultArray addObject:article];
        [[CoreDataManager sharedManager] insertArticle:article];
        dispatch_source_merge_data(source, index);
    });

    if (resultArray.count) {
        BMLog(@"数据解析插入");
//        [[ArticleManager sharedManager] insertLink:[URL absoluteString]];
    }

#if NS_BLOCKS_AVAILABLE
    block(resultArray);
#endif
}

- (NSArray *)paserPicHtml:(NSURL*)URL{

    NSData *htmlData;
    NSString *htmlStr = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error:nil];
    htmlData = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];
    OGDocument *document = [ObjectiveGumbo parseDocumentWithData:htmlData];
    NSArray *javascriptArray = [document elementsWithAttribute:@"type" andValue:@"text/javascript"];
    NSArray *jsContent = nil;
    if (javascriptArray.count > 3) {
        OGElement *jsonElement = (OGElement *)[javascriptArray objectAtIndex:2];
        NSString *jsText = [jsonElement text];
        NSArray *paramArray = [jsText componentsSeparatedByString:@";"];
        NSString *changeJsonText = [paramArray firstObject];
        changeJsonText = [changeJsonText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        changeJsonText = [changeJsonText stringByReplacingOccurrencesOfString:@"changePic.desJson = " withString:@""];
        jsContent = [changeJsonText objectFromJSONString];
    }

    OGElement *ulElement = (OGElement *)[[document elementsWithID:@"smallList"] firstObject];

    NSArray *lis = [ulElement select:@"li"];

    NSMutableArray *resultArray = [NSMutableArray arrayWithCapacity:lis.count];
    [lis enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        OGElement *liElement = obj;
        OGElement *divElement = [[liElement select:@"div"] firstObject];
        OGElement *aElement = [[divElement select:@"a"] firstObject];
        OGElement *imgElement = [[aElement select:@"img"] firstObject];

        NSString *relText = imgElement.attributes[@"rel"];
        NSString *srcText = imgElement.attributes[@"src"];
        SinglePic *pic = [[SinglePic alloc] init];
        pic.index = idx;
        pic.small = srcText;
        pic.big = relText;
        pic.link = [URL absoluteString];
        pic.cid = [self getnewNidWithLink:pic.link];
        if (idx < [jsContent count]) {
            pic.intro = [jsContent objectAtIndex:idx];
        }
//        [[ArticleManager sharedManager] insertSinglePic:pic];
        [resultArray addObject:pic];
    }];
    return resultArray;
}

- (void )paserPicListHtml:(NSURL*)URL itemsBlock:(ItemsBlock)block{
//    URL = [NSURL URLWithString:@"http://photonews.16888.com/type-5.html"];
    BMLog(@"url:%@",URL);
    NSData *htmlData;
    NSString *htmlStr = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error:nil];
    htmlData = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];

    NSString *nodeStr = nil;
    if ([[URL absoluteString] rangeOfString:@"type-5"].location != NSNotFound) {
        nodeStr = @"pic_list_g";
    }else {
        nodeStr = @"pic_list_m";
    }

    OGDocument *document = [ObjectiveGumbo parseDocumentWithData:htmlData];
    OGElement *pic_listElement = (OGElement *)[[document elementsWithClass:nodeStr] firstObject];
    OGElement *ulElement = (OGElement *)[pic_listElement first:@"ul"];
    NSArray *liArray = [ulElement select:@"li"];

    NSMutableArray *resultArray = [NSMutableArray arrayWithCapacity:liArray.count];

    dispatch_queue_t queue = dispatch_queue_create("com.iliunian.icar.data", NULL);
    dispatch_group_t group = dispatch_group_create();

    [liArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        PicModel *model = [[PicModel alloc] init];

        OGElement *liElement = (OGElement *)obj;
        OGElement *imgElement = (OGElement *)[liElement first:@"img"];

        OGElement *nameElement = (OGElement *)[[liElement elementsWithClass:@"name"] firstObject];
        NSString *link_ = nameElement.attributes[@"href"];
        dispatch_group_async(group, queue, ^{
            model.SinglePics = [self paserPicHtml:[NSURL URLWithString:link_]];
            model.total = model.SinglePics.count;
        });

        NSString *img_ = imgElement.attributes[@"_src"];
        NSString *title_ = [nameElement text];
        
        int cid = [self getnewNidWithLink:link_];

        model.cid = cid;
        model.link = link_;
        model.title = title_;
        model.thumal = img_;

        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        dispatch_group_notify(group, queue, ^{
            [resultArray addObject:model];
        });
    }];
    
#if NS_BLOCKS_AVAILABLE
    block(resultArray);
#endif
}

- (void )paserPicListHtml:(NSURL*)URL callbackBlock:(ItemsBlock)block updateItemsBlock:(ItemsBlock)updateBlock{

    BMLog(@"url:%@",URL);
    NSData *htmlData;
    NSString *htmlStr = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error:nil];
    htmlData = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];

    NSString *nodeStr = nil;
    if ([[URL absoluteString] rangeOfString:@"type-5"].location != NSNotFound) {
        nodeStr = @"pic_list_g";
    }else {
        nodeStr = @"pic_list_m";
    }

    OGDocument *document = [ObjectiveGumbo parseDocumentWithData:htmlData];
    OGElement *pic_listElement = (OGElement *)[[document elementsWithClass:nodeStr] firstObject];
    OGElement *ulElement = (OGElement *)[pic_listElement first:@"ul"];
    NSArray *liArray = [ulElement select:@"li"];

    NSMutableArray *resultArray = [NSMutableArray arrayWithCapacity:liArray.count];

    dispatch_queue_t queue = dispatch_queue_create("com.iliunian.icar.data", NULL);
    dispatch_group_t group = dispatch_group_create();

    [liArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        PicModel *model = [[PicModel alloc] init];

        OGElement *liElement = (OGElement *)obj;
        OGElement *imgElement = (OGElement *)[liElement first:@"img"];

        OGElement *nameElement = (OGElement *)[[liElement elementsWithClass:@"name"] firstObject];
        NSString *link_ = nameElement.attributes[@"href"];

        NSString *img_ = imgElement.attributes[@"_src"];
        NSString *title_ = [nameElement text];

        int cid = [self getnewNidWithLink:link_];

        model.cid = cid;
        model.link = link_;
        model.title = title_;
        model.thumal = img_;
        NSArray *array = [[ArticleManager sharedManager] singlePicsForPicture:model];
        if (array) {
            model.SinglePics = array;
            model.total = array.count;
        }
        [resultArray addObject:model];

    }];

#if NS_BLOCKS_AVAILABLE
    block(resultArray);
#endif

    [resultArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        PicModel *model = obj;
        dispatch_group_async(group, queue, ^{
            if (!model.SinglePics) {
                model.SinglePics = [self paserPicHtml:[NSURL URLWithString:model.link]];
                model.total = model.SinglePics.count;
            }
        });

    }];
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    dispatch_group_notify(group, queue, ^{
    });

#if NS_BLOCKS_AVAILABLE
    updateBlock(resultArray);
#endif


}

@end
